package com.caifu.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caifu.bean.EnumBean;
import com.caifu.enums.SysOrganization_type;
import com.caifu.pojo.SysLog;
import com.caifu.pojo.SysUser;
import com.caifu.service.SysLogService;
import com.caifu.service.SysUserService;
import com.caifu.util.DesUtil;
import com.caifu.util.Util;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import com.caifu.bean.Result;
import com.caifu.pojo.SysOrganization;
import com.caifu.service.SysOrganizationService;

import net.sf.json.JSONObject;

/**
 * 组织机构管理
 *
 * @author szt
 * @date 2020年8月5日
 */
@Controller
@RequestMapping("/org")
@PropertySource(value = {"classpath:definition.properties"},encoding = "utf-8")
public class OrganizationController extends AbstractController{
	private static final Logger logger = LoggerFactory.getLogger(OrganizationController.class);

	@Value("${file.upload.path}")
	private String fileUploadPath;
	@Autowired
	private SysOrganizationService orgService;
	@Autowired
	private SysLogService logService;
	/**
	 * 组织机构列表
	 * http://192.168.1.180:9999/ATPension/org/listPage
	 * 2020年8月5日 
	 * codeBy szt
	 */
	@RequestMapping("listPage")
	public String toBigscreenPage(Model model){
		List<Map<String, Object>> list;
		try {
			list = orgService.listSysOrganization("1", null);
			list.forEach(map->{
				map.put("type", SysOrganization_type.valueOfkey((String)map.get("type")).getValue());
				String qr_code = (String) map.get("qr_code");
				if(qr_code.length()>0){
					String arr[]=qr_code.split("\\/");
					String filename[] = arr[arr.length-1].split("\\.");
					map.put("file_name", filename[0]);
				}
			});
			model.addAttribute("orgListlv1",list);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "view/org/org_list";
	}

	/**
	 * 组织机构添加
	 * http://192.168.1.180:9999/ATPension/org/addPage
	 * 2020年8月5日
	 * codeBy szt
	 */
	@RequestMapping("addPage")
	public String addPage(Model model){
		List<Map<String, Object>> list;
		try {
			List<EnumBean> typeList = SysOrganization_type.iteratorEnum();
			JSONObject json = orgService.getAllOrganization(null);
			model.addAttribute("addOrgList", json);
			model.addAttribute("typeList", typeList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "view/org/org_add";
	}

	/**
	 * 组织机构添加
	 * http://192.168.1.180:9999/ATPension/org/editPage?orgId=105
	 * 2020年8月5日
	 * codeBy szt
	 */
	@RequestMapping("editPage")
	public String editPage(Model model, long orgId){
		List<Map<String, Object>> list;
		try {
			List<EnumBean> typeList = SysOrganization_type.iteratorEnum();
			JSONObject json = orgService.getAllOrganization(null);
			model.addAttribute("addOrgList", json);
			model.addAttribute("typeList", typeList);
			model.addAttribute("orgId",orgId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "view/org/org_add";
	}

	/**
	 * 获取组织架构列表
	 * http://192.168.1.180:9999/caifu/org/getListData?orgLevel=2&parentOrgId=100
	 * 2020年8月5日 
	 * codeBy szt
	 */
	@RequestMapping("getListData")
	@ResponseBody
	public Result<Object> getListData(String orgLevel, String parentOrgId){
		Result<Object> result = new Result<>();
		try {
			List<Map<String,Object>> list = orgService.listSysOrganization(orgLevel, parentOrgId);
			list.forEach(map->{
				map.put("type", SysOrganization_type.valueOfkey((String)map.get("type")).getValue());
				String qr_code = (String) map.get("qr_code");
				if(qr_code.length()>0){
					String arr[]=qr_code.split("\\/");
					String filename[] = arr[arr.length-1].split("\\.");
					map.put("file_name", filename[0]);
				}
			});
			result.setData(list);
			result.setCode(200);
		} catch (Exception e) {
			logger.error(e.toString());
		}
		return result;
	}

	/**
	 * 删除组织架构
	 * http://192.168.1.180:9999/caifu/org/getListData?orgId=100
	 * 2020年8月6日 
	 * codeBy szt
	 */
	@RequestMapping("delOrg")
	@ResponseBody
	public Result<Object> delOrg(String orgId){
		Result<Object> result = new Result<>();
		try {
			result = orgService.deleteSysOrganization(orgId, getUserNo());
			logService.save((SysLog) result.getData());
			result.setData(orgId);
			return result;
		} catch (Exception e) {
			logger.error(e.toString());
		}
		return result;
	}

	/**
	 * 获取所有所有组织架构
	 * http://192.168.1.180:9999/ATPension/org/getAllOrg
	 * 2020年8月6日 
	 * codeBy szt
	 */
	@RequestMapping("getAllOrg")
	@ResponseBody
	public JSONObject getAllOrg(String orgId){
		JSONObject json = new JSONObject();
		try {
			json = orgService.getAllOrganization(orgId);
		} catch (Exception e) {
			logger.error(e.toString());
		}
		return json;
	}

	/**
	 * 获取所有赋权的组织机构
	 * http://192.168.1.180:9999/ATPension/org/getAllAuthOrg?userNo=CE69C2C9575953DB
	 * 2020年8月12日 
	 * codeBy szt
	 */
	@RequestMapping("getAllAuthOrg")
	@ResponseBody
	public JSONObject getAllAuthOrg(String userNo){
		JSONObject json = new JSONObject();
		try {
			json = orgService.getAllAuthOrganization(DesUtil.decrypt(userNo),null);
		} catch (Exception e) {
			logger.error(e.toString());
		}
		return json;
	}

	/**
	 * 获取所有赋权的供餐机构（并标注已赋权过的组织）
	 * http://192.168.1.180:9999/ATPension/org/getGongcanAllAuthOrganization?userNo=CE69C2C9575953DB
	 * 2020年8月12日
	 * codeBy szt
	 */
	@RequestMapping("getGongcanAllAuthOrganization")
	@ResponseBody
	public JSONObject getGongcanAllAuthOrganization(String userNo){
		JSONObject json = new JSONObject();
		try {
			json = orgService.getGongcanAllAuthOrganization(DesUtil.decrypt(userNo),null);
		} catch (Exception e) {
			logger.error(e.toString());
		}
		return json;
	}

	/**
	 * http://192.168.1.180:9999/ATPension/org/getAllAuthTypeOrg?userNo=CCDDE32D3233705F&type=3
	 * type 1-管理 2-服务中心 3-村/社区 4-养老机构
	 * userFlag  当userNo 为空并且 userFlag 为 yes 时，默认获取当前登录用户编号
	 * 2020年8月12日
	 * codeBy szt
	 */
	@PostMapping("getAllAuthTypeOrg")
	@ResponseBody
	public JSONObject getAllAuthTypeOrg(String userNo,String type,String userFlag){
		JSONObject json = new JSONObject();
		try {
			if(StringUtils.isNotBlank(userNo)){
				userNo = DesUtil.decrypt(userNo);
			}else {
				if (StringUtils.isNotBlank(userFlag) && "yes".equals(userFlag)) {
					userNo = getUserNo() + "";
				}
			}
			json = orgService.getAllAuthTypeOrganization(userNo,type);
			//Util.pringJson(json,"arr");
		} catch (Exception e) {
			logger.error(e.toString());
		}
		return json;
	}

	/**
	 * 获取单个组织架构
	 * http://192.168.1.180:9999/caifu/org/getOrg?orgId=100
	 * 2020年8月7日 
	 * codeBy szt
	 */
	@RequestMapping("getOrg")
	@ResponseBody
	public Result<Object> getOrg(String orgId){
		Result<Object> rst = new Result<>();
		try {
			rst = orgService.getSysOrganization(orgId);
		} catch (Exception e) {
			logger.error(e.toString());
		}
		return rst;
	}

	/**
	 * 新增或修改组织架构
	 * 2020年8月7日 
	 * codeBy szt
	 */
	@PostMapping("cuOrg")
	@ResponseBody
	public Result cuOrg( SysOrganization org) {
		Result rst = new Result<>();
		try {
			if (org.getOrgId()!=null) {
				rst = orgService.updateSysOrganization(org, getUserNo());
			} else {
				rst = orgService.addSysOrganization(org, getUserNo());
			}
			logService.save((SysLog) rst.getData());
			return rst;
		} catch (Exception e) {
			logger.error(e.toString());
		}
		return rst;
	}


	@GetMapping("updateQr")
	@ResponseBody
	public Result updateQr( ) {
		Result rst = new Result<>();
		try {
			orgService.updateQr();
			rst.setCode(200);
			rst.setMsg("成功！");
			return rst;
		} catch (Exception e) {
			logger.error(e.toString());
		}
		return rst;
	}

	/**
	 * 二维码下载
	 * 192.168.1.180:9999/ATPension/org/qrdownload?fileName=1141101604916083411
	 * 2020年11月20日
	 * codeBy szt
	 */
	@RequestMapping(value = { "/qrdownload" }, method = RequestMethod.GET)
	public ResponseEntity<byte[]> download(String fileName) throws IOException {
		String filePath = fileUploadPath + "/organization/" + fileName + ".png";
		InputStream in = new FileInputStream(new File(filePath));// 将该文件加入到输入流之中
		byte[] body = null;
		body = new byte[in.available()];// 返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取（或跳过）的估计剩余字节数
		in.read(body);// 读入到输入流里面

		fileName = new String(fileName.getBytes("gbk"), "iso8859-1");// 防止中文乱码
		HttpHeaders headers = new HttpHeaders();// 设置响应头
		headers.add("Content-Disposition", "attachment;filename=" + fileName+".png");
		headers.add("content-type","image/png");
		HttpStatus statusCode = HttpStatus.OK;// 设置响应吗
		ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode);
		return response;
	}
}
